package com.woniuxy.usercoachassemble.controller;

import com.woniuxy.usercoachassemble.commons.*;
import com.woniuxy.usercoachassemble.entity.CoachInfo;
import com.woniuxy.usercoachassemble.entity.CoachTime;
import com.woniuxy.usercoachassemble.entity.User;
import com.woniuxy.usercoachassemble.entity.Userinfo;
import com.woniuxy.usercoachassemble.service.CoachInfoService;
import com.woniuxy.usercoachassemble.service.CoachTimeService;
import com.woniuxy.usercoachassemble.service.UserService;
import com.woniuxy.usercoachassemble.service.UserinfoService;
import org.example.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: LoginAfterFinishInfoController
 * Description: 登录后完善信息
 * date: 2020/7/17 14:23
 *
 * @author Fy浪迹、
 */
@RestController
@RequestMapping("finishInfo")
public class LoginAfterFinishInfoController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserinfoService userinfoService;

    @Autowired
    private CoachInfoService coachInfoService;

    @Autowired
    private CoachTimeService coachTimeService;

    // 登录后完善用户信息
    @RequestMapping("finishStudentInfo")
    public Result finishInfoStudent(HttpServletRequest request,@RequestParam("file") MultipartFile file, String tel, String code, String nickname, Integer infoLevel,String username) throws IOException {
        // 从session中的获取的user_id
        Integer user_id = Integer.parseInt(request.getHeader("userId"));

        User user = userService.selectUserById(user_id);

        Userinfo userinfo = new Userinfo();
        userinfo.setUserId(user_id);


        if(!ValidatorUtils.isNullOrEmpty(nickname)){
            userinfo.setNickname(nickname);
        }
        
        if(ValidatorUtils.isNullOrEmpty(user.getTel())){
            if(ValidatorUtils.isNullOrEmpty(tel)){
                return Result.Error(600,"手机号码不能为空");
            }

            User user1 = userService.selectUserByTel(tel);
            if(user1 != null){
                return Result.Error(600,"该手机号已经绑定账号!");
            }


            // 判断验证码是否正确
            ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
            String telCode = opsForValue.get(ConstantPool.TEL_BINDING_PREFIX + tel);
            if(ValidatorUtils.isNullOrEmpty(telCode)){
                return Result.Error(600,"验证码已失效");
            }
            user.setTel(tel);
        }

        if(infoLevel == null || !(infoLevel >=1 && infoLevel <= 3)){
            return Result.Error(600,"信息公开参数错误");
        }

        if(ValidatorUtils.isNullOrEmpty(username)){
            return Result.Error(600,"用户名不能为空");
        }
        User user1 = userService.selectUserByUsername(username);

        if(user1 != null){
            return Result.Error(600,"用户名已经存在");
        }

        user.setUsername(username);

        userinfo.setInfoLevel(infoLevel);

        if(file != null){
            InputStream inputStream = file.getInputStream();
            // 获取上传文件的名称
            String fileName = file.getOriginalFilename();

            // 获取文件的后缀
            String ext = fileName.substring(fileName.lastIndexOf("."));

            String newFilename = UUIDUtils.getUUID() + ext;
            // 存入服务器
            QiNiuUtils.uploadQNImg(inputStream,newFilename);
            userinfo.setHeadPortrait(QiNiuUtils.fullPath(newFilename));
        }

        user.setA(2);
        // 更新user
        userService.updateById(user);


        // 更新
        userinfoService.update(userinfo,userinfoService.update().eq("user_id",user_id).getWrapper());

        return  Result.Success("修改成功");
    }

    // 登录后完善教练信息
    @RequestMapping("finishCoachInfo")
    public Result finishCoachInfo (HttpServletRequest request,@RequestParam("file") MultipartFile file, String tel, String code, String nickname, Integer infoLevel, Integer charge, Integer genreId,Integer telLevel,Integer personalTrainer,String username,String realName,Integer[] time) throws IOException {
        // 从session中的获取的user_id
        Integer user_id = Integer.parseInt(request.getHeader("userId"));

        User user = userService.selectUserById(user_id);

        Userinfo userinfo = new Userinfo();
        userinfo.setUserId(user_id);


        if(!ValidatorUtils.isNullOrEmpty(nickname)){
            userinfo.setNickname(nickname);
        }

        if(ValidatorUtils.isNullOrEmpty(user.getTel())){
            if(ValidatorUtils.isNullOrEmpty(tel)){
                return Result.Error(600,"手机号码不能为空");
            }

            if(ValidatorUtils.isNullOrEmpty(code)){
                return Result.Error(600,"验证码不能为空");
            }
            // 判断验证码是否正确
            ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
            String telCode = opsForValue.get(ConstantPool.TEL_BINDING_PREFIX + tel);
            if(ValidatorUtils.isNullOrEmpty(telCode)){
                return Result.Error(600,"验证码已失效");
            }
            user.setTel(tel);
        }


        if(ValidatorUtils.isUsername(username)){
            return Result.Error(600,"用户名不能为空");
        }

        User user1 = userService.selectUserByUsername(username);

        if(user1 != null){
            return Result.Error(600,"用户名已经存在");
        }

        user.setUsername(username);

        if(!ValidatorUtils.isNullOrEmpty(realName)){
            userinfo.setRealName(realName);
        }


        if(infoLevel == null || !(infoLevel >=1 && infoLevel <= 3)){
            return Result.Error(600,"信息公开参数错误");
        }
        userinfo.setInfoLevel(infoLevel);




        CoachInfo coachInfo = coachInfoService.query().eq("user_id", user_id).one();
        // 收费标准
        if(!(charge != null && charge >= 0)){
            return  Result.Error(600,"收费标准参数格式错误");
        }
        coachInfo.setCharge(charge);
        // 流派
        if(genreId != null && genreId > 0){
            coachInfo.setGenreId(genreId);
        }

        // 电话公开等级
        if(telLevel !=null && telLevel>0){
            coachInfo.setTelLevel(telLevel);
        }

        // 是否接课
        if(personalTrainer != null && personalTrainer > 0){
            coachInfo.setPersonalTrainer(1);
        }

        // 空闲时间
        if(time == null || time.length == 0){
            Result.Error(600,"您还没有选择空闲时间");
        }

        ArrayList<CoachTime> coachTimes = new ArrayList<>();
        for (int i = 1;i < 6;i++){
            for (Integer t:time){
                CoachTime coachTime = new CoachTime();
                coachTime.setCoachId(user.getUserId());
                coachTime.setTimeId(t);
                coachTime.setWeek(i);
                coachTime.setStatus(1);
                coachTimes.add(coachTime);
            }
        }
        boolean b = coachTimeService.saveBatch(coachTimes);
        if(!b){
            return  Result.Error(500,"服务器繁忙!");
        }




        if(file != null){
            InputStream inputStream = file.getInputStream();
            // 获取上传文件的名称
            String fileName = file.getOriginalFilename();

            // 获取文件的后缀
            String ext = fileName.substring(fileName.lastIndexOf("."));

            String newFilename = UUIDUtils.getUUID() + ext;
            // 存入服务器
            QiNiuUtils.uploadQNImg(inputStream,newFilename);
            userinfo.setHeadPortrait(QiNiuUtils.fullPath(newFilename));
        }








        user.setA(2);
        // 更新user
        userService.updateById(user);

        // 更新userinfo
        userinfoService.update(userinfo,userinfoService.update().eq("user_id",user_id).getWrapper());

        // 更新coachInfo
        coachInfoService.updateById(coachInfo);


        return  Result.Success("修改成功");
    }


    // 登录后完善场馆信息
    @RequestMapping("finishGymInfo")
    public Result finishGymInfo(HttpServletRequest request, @RequestParam("file") MultipartFile file,String tel,String code,String nickname,Integer infoLevel,String username,String realName,Integer charge,Integer personalTrainer,Integer genreId,Integer telLevel) throws IOException {
        // 从session中的获取的user_id
        Integer user_id = Integer.parseInt(request.getHeader("userId"));

        User user = userService.selectUserById(user_id);

        Userinfo userinfo = userinfoService.query().eq("user_id",user_id).one();
        userinfo.setUserId(user_id);


        if(!ValidatorUtils.isNullOrEmpty(nickname)){
            userinfo.setNickname(nickname);
        }

        if(ValidatorUtils.isNullOrEmpty(user.getTel())){
            if(ValidatorUtils.isNullOrEmpty(tel)){
                return Result.Error(600,"手机号码不能为空");
            }

            if(ValidatorUtils.isNullOrEmpty(code)){
                return Result.Error(600,"验证码不能为空");
            }

            // 判断验证码是否正确
            ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
            String telCode = opsForValue.get(ConstantPool.TEL_BINDING_PREFIX + tel);
            if(ValidatorUtils.isNullOrEmpty(telCode)){
                return Result.Error(600,"验证码已失效");
            }
            user.setTel(tel);
        }

        if(infoLevel == null || !(infoLevel >=1 && infoLevel <= 3)){
            return Result.Error(600,"信息公开参数错误");
        }
        userinfo.setInfoLevel(infoLevel);

//      String username,String realName,Integer charge,
        if(ValidatorUtils.isNullOrEmpty(username)){
            return  Result.Error(600,"您还没有填写用户名!");
        }

        user.setUsername(username);

        // 真实姓名
        if(!ValidatorUtils.isNullOrEmpty(realName)){
            userinfo.setRealName(realName);
        }

        CoachInfo coachInfo = coachInfoService.query().eq("user_id",user_id).one();

        // 收费标准
        if(charge == null || charge == 0){
            return  Result.Error(600,"您还没有填写收费标准!");
        }
        coachInfo.setCharge(charge);
        
        // Integer personalTrainer,Integer genreId,Integer telLevel

        // 是否接私课
        if(personalTrainer != null && personalTrainer !=0){
            coachInfo.setPersonalTrainer(personalTrainer);
        }

        // 流派
        if(genreId != null && genreId != 0){
            coachInfo.setGenreId(genreId);
        }

        // 电话公开等级
        if(telLevel != null && telLevel != 0){
            coachInfo.setTelLevel(telLevel);
        }


        if(file != null){
            InputStream inputStream = file.getInputStream();
            // 获取上传文件的名称
            String fileName = file.getOriginalFilename();

            // 获取文件的后缀
            String ext = fileName.substring(fileName.lastIndexOf("."));

            String newFilename = UUIDUtils.getUUID() + ext;
            // 存入服务器
            QiNiuUtils.uploadQNImg(inputStream,newFilename);
            userinfo.setHeadPortrait(QiNiuUtils.fullPath(newFilename));
        }




        // 更新user
        userService.updateById(user);
        // 更新教练
        coachInfoService.updateById(coachInfo);
        // 更新
        userinfoService.updateById(userinfo);

        return  Result.Success("修改成功");
    }

    /**
     * @description:TODO(获取绑定手机验证码)
     * @param tel
     * @return:  org.example.Result
     * @author: Fy浪迹、
     * @date: 2020/7/17 14:29
     */
    @RequestMapping("getBindingCode")
    public Result getBindingCode(String tel){

        // 校验电话号码格式是否正确
        if(tel == null || tel.isEmpty() || !ValidatorUtils.isMobile(tel)){
            return Result.Error(600,"电话格式错误");
        }

        // 判断电话号码是否存在
        User userRegister = userService.selectUserByTel(tel);
        if(userRegister != null){
            return Result.Error(600,"该电话号码已绑定!");
        }

        // 随机生成6位数code
        String code = RandomUtils.get6PlaceNum() + "";
        System.out.println("手机登录验证码"+code);
        // 发送短信 电话号码,发送模板:注册,验证码
//        boolean b = SMSUtils.sendSMS(tel, SMSUtils.TEMPLATECODE_LOGIN, code);
        boolean b = true;
        if(!b){
            return Result.Error(600,"发送失败");
        }

        // 将手机号code 存入redis
        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        opsForValue.set(ConstantPool.TEL_BINDING_PREFIX+tel,code,3, TimeUnit.MINUTES);
        Result success = Result.Success();
        success.setMessage("验证码已发送");
        return success;
    }
}
